package org.wmq.shopmanager.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.wmq.commonutil.constant.RedisConstant;
import org.wmq.shopmanager.service.ValidateCodeService;
import org.wmq.shopmodel.VO.system.ValidateCodeVO;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class ValidateCodeServiceImpl implements ValidateCodeService {
    private final StringRedisTemplate redisTemplate;

    @Override
    public ValidateCodeVO generateValidateCode() {
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(150, 48, 4, 5);
        String codeValue = circleCaptcha.getCode();
        String codeKey = UUID.randomUUID().toString();
        this.redisTemplate.opsForValue().set(RedisConstant.VALIDATE_CODE_CACHE_PREFIX + codeKey, codeValue, RedisConstant.VALIDATE_CODE_EXPIRE_MS, TimeUnit.MILLISECONDS);
        ValidateCodeVO result = new ValidateCodeVO();
        result.setCodeKey(codeKey);
        result.setCodeValue("data:image/png;base64," + circleCaptcha.getImageBase64());
        return result;
    }
}
